/**
 * 本地缓存配置
 */
import { DEFAULT_CACHE_TIME } from '/@/settings/encryptionSetting';
import { base_key } from '/@/common/constant/cacheConst';
import { isNullOrUnDef } from '/@/common/util/is';

//Partial: 本地对象，允许设置对象中的部分属性
export type Options = Partial<CreateStorageParams>;
export interface CreateStorageParams {
    prefixKey: string;
    storage: Storage;
    hasEncrypt: boolean;
    timeout?: Nullable<number>;
}

// 创建本地缓存
export const createLocalStorage = (options: Options = {}) => {
    options.prefixKey = base_key;
    const WebStorage = class WebStorage {
        private storage: Storage;
        private prefixKey?: string;

        constructor() {
            this.storage = localStorage;
            this.prefixKey = options.prefixKey;
        }

        private getKey(key: string) {
            return `${this.prefixKey}${key}`;
        }

        //设置值
        set(key: string, value: any, expire?: number | null) {
            const stringData = JSON.stringify({
                value,
                time: Date.now(),
                expire: !isNullOrUnDef(expire) ? new Date().getTime() + expire * 1000 : null,
            });
            this.storage.setItem(this.getKey(key), stringData);
        }

        //获取值
        get(key: string, def: any = null): any {
            const val = this.storage.getItem(this.getKey(key));
            if (!val) return def;
            try {
                const data = JSON.parse(val);
                const { value, expire } = data;
                if (isNullOrUnDef(expire) || expire >= new Date().getTime()) {
                    return value;
                }
                this.remove(key);
            } catch (e) {
                return def;
            }
        }

        //删除key
        remove(key: string) {
            this.storage.removeItem(this.getKey(key));
        }

        //删除所有
        clear(): void {
            this.storage.clear();
        }
    };
    return new WebStorage();
};

const cls = createLocalStorage();

//设置本地对象
export function setAuthCache(key, value) {
    cls.set(key, value);
}

//获取本地对象
export function getAuthCache<T>(key) {
    const res = cls.get(key);
    return res as T;
}

//移除key
export function removeAuthCache(key) {
    cls.remove(key);
}